from django.http import HttpResponse
import re

# post接口类
from django.utils.decorators import method_decorator
from django.views.decorators.csrf import csrf_exempt

from urllib.parse import unquote

ILLEGAL_VALUE = 'false'
LEGAL_VALUE = 'true'

# 两个列表 闰年/非闰年
LEAP_YEAR = [[1, 31], [1, 29], [1, 31], [1, 30], [1, 31], [1, 30], [1, 31], [1, 31], [1, 30], [1, 31], [1, 30], [1, 31]]
NON_LEAP_YEAR = [[1, 31], [1, 28], [1, 31], [1, 30], [1, 31], [1, 30], [1, 31], [1, 31], [1, 30], [1, 31], [1, 30],
                 [1, 31]]


@method_decorator(csrf_exempt, name='dispatch')
def valdator(request):
    if request.method == 'POST':
        # 根据POST请求获取日期参数
        data = request.body.decode()
        time_str = unquote(data).replace("'", '')
        print("原始字符串：", time_str, type(time_str))

        # TODO 提取字符串 getRegTime()
        # getRegTime需要很强大才行
        time_dict = getRegTime(time_str)
        print("字典：", time_dict)
        result = '一些提示信息'
        if time_dict:
            # TODO 通过参数time_dict，判断是否是合法日期
            result = judgeTimeStr(time_dict)
            # test output
            print(result)
        return HttpResponse(result)
    else:
        return HttpResponse('hello!')


def getRegTime(timestr):
    """
    getRegTime作为转换标准时间的函数，
    把所有的时间转成一个字典，分别对应 --> 年 月 日 时 分 秒
    :return: 
    """
    # 空字典，存储年月日
    time_dic = {'year': None, 'month': None, 'day': None, 'hour': None, 'minute': None, 'second': None, }

    # 2019/1/1 2019-1-1 年月日格式
    pattern = re.compile('\{date:(\d{4})\/(\d{1,2})\/(\d{1,2})\}')
    result = re.findall(pattern, timestr)
    if result:
        time_dic['year'] = result[0][0]
        time_dic['month'] = result[0][1]
        time_dic['day'] = result[0][2]
        return time_dic

    # 2019/1/1 10:07:25  2019-1-1 10:07:25 日期 和 时间
    # TODO 是否能够简化正则表达式，把重复的化简一下
    pattern = re.compile('\{date:(\d{4})[\/|\-](\d{1,2})[\/|\-](\d{1,2})\s+(\d{1,2}):(\d{1,2}):(\d{1,2})\}')
    result = re.findall(pattern, timestr)
    if result:
        time_dic['year'] = result[0][0]
        time_dic['month'] = result[0][1]
        time_dic['day'] = result[0][2]
        time_dic['hour'] = result[0][3]
        time_dic['minute'] = result[0][4]
        time_dic['second'] = result[0][5]
        return time_dic

    # 2019/11/01 10:07:25 AM / PM
    pattern = re.compile(
        '\{date:(\d{4})[\/|\-](\d{1,2})[\/|\-](\d{1,2})\s+(\d{1,2}):(\d{1,2}):(\d{1,2})\s+(A|P|a|p)(M|m)\}')
    result = re.findall(pattern, timestr)
    if result:
        time_dic['year'] = result[0][0]
        time_dic['month'] = result[0][1]
        time_dic['day'] = result[0][2]
        # 加12 如果超过则这个是不标准的时间
        time_dic['hour'] = int(result[0][3]) + 12
        time_dic['minute'] = result[0][4]
        time_dic['second'] = result[0][5]
        return time_dic

    # UTC / GTM / +0800UTC
    pattern = re.compile(
        '\{date:(\d{4})[\/|\-](\d{1,2})[\/|\-](\d{1,2})\s+(\d{1,2}):(\d{1,2}):(\d{1,2})\s+(UTC|GTM|\+0800\s+UTC)\}')
    result = re.findall(pattern, timestr)
    if result:
        time_dic['year'] = result[0][0]
        time_dic['month'] = result[0][1]
        time_dic['day'] = result[0][2]
        time_dic['hour'] = result[0][3]
        time_dic['minute'] = result[0][4]
        time_dic['second'] = result[0][5]
        return time_dic

    # Oct 7,1970 5:57:51 PM  /  September 17,2012 10:09 am 月份简写
    # TODO 需求扩展的话，可以增加字典中的数据
    mon = {
        'Jan': 1,
        'Feb': 2,
        'Mar': 3,
        'Apr': 4,
        'May': 5,
        'June': 6,
        'July': 7,
        'Aug': 8,
        'Sep': 9,
        'Oct': 10,
        'Nov': 11,
        'Dec': 12,
        'January': 1,
        'February': 2,
        'March': 3,
        'April': 4,
        'August': 8,
        'September': 9,
        'October': 10,
        'November': 11,
        'December': 12,
    }
    pattern = re.compile(
        '\{date:([a-zA-Z]{3,9})\s+(\d{1,2}),(\d{4})\s+(\d{1,2}):(\d{1,2}):(\d{1,2})\s+[A|P|a|p][M|m]\}')
    result = re.findall(pattern, timestr)
    # test output
    print(result)
    if result:
        time_dic['year'] = result[0][2]
        time_dic['month'] = None if result[0][0] not in mon else mon[result[0][0]]
        time_dic['day'] = result[0][1]
        time_dic['hour'] = int(result[0][3]) + 12
        time_dic['minute'] = result[0][4]
        time_dic['second'] = result[0][5]
        return time_dic

    # Oct 7,1970 5:57 PM  /  September 17,2012 10:09 am 月份简写
    pattern = re.compile(
        '\{date:([a-zA-Z]{3,9})\s+(\d{1,2}),(\d{4})\s+(\d{1,2}):(\d{1,2})\s+[A|P|a|p][M|m]\}')
    result = re.findall(pattern, timestr)
    # test output
    print(result)
    if result:
        time_dic['year'] = result[0][2]
        time_dic['month'] = None if result[0][0] not in mon else mon[result[0][0]]
        time_dic['day'] = result[0][1]
        time_dic['hour'] = int(result[0][3]) + 12
        time_dic['minute'] = result[0][4]
        return time_dic

    # 12 Feb 2006 15:04:05
    pattern = re.compile(
        '\{date:(\d{1,2})\s+([a-zA-Z]{3,4})\s+(\d{4}),(\d{1,2}):(\d{1,2}):(\d{1,2})\}')
    result = re.findall(pattern, timestr)
    # test output
    print(result)
    if result:
        time_dic['year'] = result[0][2]
        time_dic['month'] = None if result[0][1] not in mon else mon[result[0][1]]
        time_dic['day'] = result[0][0]
        time_dic['hour'] = result[0][3]
        time_dic['minute'] = result[0][4]
        time_dic['second'] = result[0][5]
        return time_dic

    # Mon, 02 Jan 2006 15:04:05
    pattern = re.compile(
        '\{date:([a-zA-Z]{3,4}),\s+(\d{1,2})\s+([a-zA-Z]{3,4})\s+(\d{4})\s+(\d{1,2}):(\d{1,2}):(\d{1,2})\}')
    result = re.findall(pattern, timestr)
    # test output
    print(result)
    if result:
        week = result[0][0]
        time_dic['year'] = result[0][3]
        time_dic['month'] = None if result[0][2] not in mon else mon[result[0][2]]
        time_dic['day'] = result[0][1]
        time_dic['hour'] = result[0][4]
        time_dic['minute'] = result[0][5]
        time_dic['second'] = result[0][6]
        if week == judgeWeek(int(time_dic['year']), int(time_dic['month']),int(time_dic['day'])):
            return time_dic
        else:
            return None
    # TODO 如果以上的结果都没有被匹配到，返回的是一个空字典，需要给用户点提示信息
    return None


def judgeTimeStr(dic):
    """
    判断逻辑
    参数是一个已经被处理好的日期字典
    :param dic:
    :return:
    """
    # 如果传过来的数据不是None
    try:
        year = int(dic['year']) if dic['year'] else None
        month = int(dic['month']) if dic['month'] else None
        day = int(dic['day']) if dic['day'] else None
        hour = int(dic['hour']) if dic['hour'] else None
        minute = int(dic['minute']) if dic['minute'] else None
        second = int(dic['second']) if dic['second'] else None
    except TypeError as e:
        print("时间格式异常错误！")
        print(e)
        return ILLEGAL_VALUE
    except Exception as e:
        print(e)
        return ILLEGAL_VALUE
    finally:
        pass

    # 如果有一个不合法，即为不合法时间
    # 年月日 and 年月日时分秒
    if not 1900 <= year <= 2090 or not 1 <= month <= 12 or not 1 <= day <= 31:
        return ILLEGAL_VALUE
    # 这里的时间可能为0 所以判断条件是判空 None
    if hour is not None and minute is not None:
        if second is not None:
            if not 0 <= hour <= 23 or not 0 <= minute <= 59 or not 0 <= second <= 59:
                return ILLEGAL_VALUE
        else:
            if not 0 <= hour <= 23 or not 0 <= minute <= 59:
                return ILLEGAL_VALUE
    """
    通过上面这个if语句的判断，已经把基本合法的日期给筛选出来了。
    现在的问题是判断闰年问题。
    """
    # print(year, ' ', month, ' ', day, ' ', hour, ' ', minute, ' ', second)
    # TODO 判断是否是一个合法的年月日
    if (year % 4 == 0 and year % 100 != 0) or year % 400 == 0:
        # TODO 闰年
        # 判断month对应的是否是合法的day
        if LEAP_YEAR[month - 1][0] <= day <= LEAP_YEAR[month - 1][1]:
            return LEGAL_VALUE
        else:
            return ILLEGAL_VALUE
    else:
        # TODO 非闰年
        # 判断month对应的是否是合法的day
        if NON_LEAP_YEAR[month - 1][0] <= day <= NON_LEAP_YEAR[month - 1][1]:
            return LEGAL_VALUE
        else:
            return ILLEGAL_VALUE


import datetime


def judgeWeek(year, month, day):
    whatday = datetime.datetime(year, month, day).strftime("%a")
    return whatday
